package com.rc.evcharger.protocol.ylevcharger.service;

import com.rc.evcharger.common.constant.SocketConstant;
import com.rc.evcharger.common.utils.DataUtil;
import com.rc.evcharger.mapper.enterprise.EnterpriseMemberMapper;
import com.rc.evcharger.mapper.member.MemberAccountMapper;
import com.rc.evcharger.mapper.rc.RcMemberFlagMapper;
import com.rc.evcharger.model.elec.ElecPile;
import com.rc.evcharger.model.enterprise.EnterpriseMember;
import com.rc.evcharger.model.member.MemberAccount;
import com.rc.evcharger.model.member.MemberInfo;
import com.rc.evcharger.model.rc.RcMemberFlag;
import com.rc.evcharger.redis.RedisService;
import com.rc.evcharger.service.elec.ElecPileService;
import com.rc.evcharger.service.enterprise.EnterpriseSubmemberShareService;
import com.rc.evcharger.service.member.MemberInfoService;
import com.rc.evcharger.service.order.OrderInfoService;
import com.rc.evcharger.service.tenant.TenantSettingService;
import com.rc.evcharger.vo.charge.StartChargeReq;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;

/**
 * Create by Yang on 2021/11/20
 */
@Component
public class CommandCommonServiceImpl implements CommandCommonService {
    private static Logger logger = LoggerFactory.getLogger(CommandCommonServiceImpl.class);

    @Autowired
    private ElecPileService elecPileService;

    @Autowired
    private MemberInfoService memberInfoService;

    @Autowired
    private MemberAccountMapper memberAccountMapper;

    @Autowired
    private EnterpriseSubmemberShareService enterpriseSubmemberShareService;

    @Autowired
    private TenantSettingService tenantSettingService;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private EnterpriseMemberMapper enterpriseMemberMapper;

    @Autowired
    private RcMemberFlagMapper rcMemberFlagMapper;

    /**
     * 充电前,会员信息校验
     *
     * @param startChargeRequest
     * @return
     */
    @Override
    public Integer checkStart(StartChargeReq startChargeRequest) {
        ElecPile pile = elecPileService.selectByPrimaryKey(startChargeRequest.getElecPileId());
        MemberInfo memberInfo = memberInfoService.selectByPrimaryKey(startChargeRequest.getMemberId());

        //判断是个人钱包还是企业钱包; 0个人钱包 1企业钱包 默认0
        BigDecimal money = null;
        if ((SocketConstant.CON0 + "").equals(startChargeRequest.getAccountType())) {
            money = memberInfo.getJoinMemberAccount().getAccount();
        } else if ("1".equals(startChargeRequest.getAccountType())){
            RcMemberFlag rcMemberFlag = rcMemberFlagMapper.selectByPrimaryKey(memberInfo.getMemberId());
            EnterpriseMember enterpriseMember = enterpriseMemberMapper.selectByPrimaryKey(rcMemberFlag.getEnterpriseId());
            //企业余额加授信剩余额度
            money = enterpriseMember.getEnterpriseAccount().add(enterpriseMember.getRemainCreditAmount());
        }else {
            //共享钱包
            money = memberInfo.getJoinMemberAccount().getPaymentRefundAccount();
        }

        //单冲用户最小启动充电余额
        BigDecimal start_charge_account_limit = tenantSettingService.query_start_charge_account_limit(memberInfo.getTenantCode());

        //用户是否在充电 0不是，1正充电                         充电类型 0单冲 1多充 默认0
        if ("1".equals(memberInfo.getChargeStatus()) && "0".equals(memberInfo.getChargeType())) {
            return SocketConstant.USING;
            // 1多充
        } else if (memberInfo.getChargeType().equals(SocketConstant.CON1 + "")) {
            Integer number = orderInfoService.countElecOrder(memberInfo) + 1;

            //一号多充金额限制
            BigDecimal mult_charge_account_limit = tenantSettingService.query_mult_charge_account_limit(memberInfo.getTenantCode());
            BigDecimal startMoney = mult_charge_account_limit.multiply(new BigDecimal(number));
            //多充 一车充电与普通用户一致
            if (number == 1) {
                startMoney = start_charge_account_limit;
            }
            //多充会员启动的余额大于  单次启动金额*（正在充电订单数+1）
            if (startMoney.compareTo(money) == 1) {
                return SocketConstant.EXCEPTION;
            }
        }

        //如果没有参数值,就取默认值
        //PlatformSetting platformSetting = platformSettingService.selectSettingByParaName(PlatformConstant.START_CHARGE_ACCOUNT_LIMIT);
        //BigDecimal start_charge_account_limit = PlatformConstant.DEFALUT_START_CHARGE_ACCOUNT_LIMIT;
        //try {
        //    if (platformSetting != null) {
        //        start_charge_account_limit = new BigDecimal(platformSetting.getParaValue());
        //    }
        //} catch (Exception e) {
        //    logger.error("start_charge_account_limit 无效", e);
        //}


        if (money == null || money.intValue() < start_charge_account_limit.intValue()) {
            logger.warn("钱包余额2:" + money);
            return SocketConstant.EXCEPTION;
        }

        //添加枪约束;
        String duplicationClickTime = redisService.getRedis(DataUtil.getCheckPileTime(pile.getPileRtua(), startChargeRequest.getGunNum()));
        if (duplicationClickTime != null) {
            Long timeDiff = (System.currentTimeMillis() - Long.valueOf(duplicationClickTime)) / 1000;
            if (timeDiff < 8) {
                redisService.putRedis(DataUtil.getCheckPileTime(pile.getPileRtua(), startChargeRequest.getGunNum()), String.valueOf(new Date().getTime()));
                logger.warn("充电失败,充电约束的值为duplicationClickTime=" + duplicationClickTime);
                return SocketConstant.UNIQUE;
            }
        }

        redisService.putRedis(DataUtil.getCheckPileTime(pile.getPileRtua(), startChargeRequest.getGunNum()), String.valueOf(new Date().getTime()));

        return SocketConstant.SUCCESS;
    }
}
